package com.example.custsecurity.security.config;

import com.alibaba.fastjson.JSONObject;
import com.example.custsecurity.security.jwt.CustJwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

//认证成功
@Component
public class CustSuccessfulHandler implements AuthenticationSuccessHandler{

    @Autowired
    private CustJwtService custJwtService;

        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException{

            //  验证如果以携带token进行登录，就不要发放新的jwt token令牌
            String head_token = request.getHeader("Authentication");

            if (head_token==null){
                head_token = custJwtService.obtainToken(authentication);
            }

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",HttpServletResponse.SC_OK);
            jsonObject.put("token",head_token);
            jsonObject.put("msg","登陆成功");

            pw.print(jsonObject);
            pw.flush();
            pw.close();
//        response.sendError(HttpServletResponse.SC_OK,"{'code':200,'msg':'登陆成功'}");
        }

}
